import React from 'react';
import router from 'umi/router';
import { connect } from 'dva';
import { InboxOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Steps, Button, message, Upload, Modal, Progress } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import downloadFile, { urlParse } from '@/utils/utils';

const { Step } = Steps;
const { Dragger } = Upload;

@connect(({ supplybilling }) => ({
  supplybilling,
}))
@Form.create()
class SelectSteps extends React.Component {
  state = {
    splitType: '1',
    billId: '1',
    fileList: [],
    uploading: false,
    modalVisible: false,
    progressPercent: 0,
  };

  componentDidMount() {
    const { location } = this.props;
    const { splitType, billId } = this.state;
    const splitTypes = urlParse(location.search).splitType
      ? urlParse(location.search).splitType
      : splitType;
    const billIds = urlParse(location.search).billId ? urlParse(location.search).billId : billId;
    this.setState({ splitType: splitTypes, billId: billIds });
  }

  // 下载模板
  exportExcel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'supplybilling/updownfiles',
      payload: {},
    }).then(res => {
      if (res.success) {
        const fileInfo = res.data.split('|');
        downloadFile({ fileId: fileInfo[0], fileName: fileInfo[1] });
      } else {
        message.warning(res.message || '下载失败');
      }
    });
  };

  // 文件上传
  handleUpload = () => {
    const { fileList, splitType, billId } = this.state;
    const { dispatch } = this.props;
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append('file', file);
    });
    formData.append('billId', billId);
    this.setState({
      uploading: true,
    });

    dispatch({
      type: 'publicdata/uploadFile',
      uploadUrl: '/csApi/nsBill/splitEmp',
      payload: formData,
      callback: res => {
        if (res.billId) {
          window.localStorage.setItem('billUploadData', JSON.stringify({ ...res, splitType }));
          router.push(`/chargemanage/supplybilling/finish`);
        } else {
          message.warning(res.message || res.errorInfo || '上传失败，请参照模板内容正确上传');
          this.setState({
            fileList: [],
            uploading: false,
          });
        }
      },
    });
  };

  render() {
    const { uploading, fileList, modalVisible, progressPercent } = this.state;
    const props = {
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        if (fileList.length === 1) {
          message.warning('建议只能上传一个文件');
          return false;
        }
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
    };
    return (
      <PageHeaderWrapper>
        <Card>
          <Steps current={1}>
            <Step title="选择拆分类型" />
            <Step title="员工拆分" />
            <Step title="完成" />
          </Steps>
          <Button
            type="primary"
            style={{ display: 'block', margin: '50px auto' }}
            onClick={this.exportExcel}
          >
            下载模板
          </Button>
          <div style={{ width: 480, height: 200, margin: '0 auto' }}>
            <Dragger {...props}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">点击或将文件拖拽到这里上传</p>
            </Dragger>
          </div>
          <div style={{ marginTop: '50px', marginBottom: '30px', textAlign: 'center' }}>
            <Button style={{ marginRight: '30px' }} onClick={() => window.history.back()}>
              上一步
            </Button>
            <Button
              type="primary"
              disabled={fileList.length === 0}
              loading={uploading}
              onClick={this.handleUpload}
            >
              提交
            </Button>
          </div>
        </Card>
        <Modal
          title="拆单任务"
          footer={null}
          closable={false}
          visible={modalVisible}
          onCancel={() => this.setState({ modalVisible: false })}
        >
          <div style={{ textAlign: 'center' }}>
            <Progress percent={progressPercent} format={percent => `${percent}%`} />
          </div>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
export default SelectSteps;
